package world.liuru.poem.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import world.liuru.poem.entity.Poem;
import world.liuru.poem.repository.PoemRepository;
import world.liuru.poem.service.PoemService;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class PoemServiceImpl implements PoemService {

    @Resource
    PoemRepository poemRepository;
    @Override
    public Poem insertPoem(Poem poem) {
        return poemRepository.save(poem);
    }

    @Override
    public void deletePoem(String id) {
        poemRepository.deleteById(id);
    }

    @Override
    public Poem updatePoem(Poem poem) {
        String id = poem.getId();
        Poem poemOld = this.findPoemById(id);
        if (Objects.isNull(poem.getAuthor())){
            poem.setAuthor(poemOld.getAuthor());
        }
        if (Objects.isNull(poem.getBackground())){
            poem.setBackground(poemOld.getBackground());
        }
        if (Objects.isNull(poem.getContent())){
            poem.setContent(poemOld.getContent());
        }
        if (Objects.isNull(poem.getCreateDate())){
            poem.setCreateDate(poemOld.getCreateDate());
        }
        if (Objects.isNull(poem.getImgUrl())){
            poem.setImgUrl(poemOld.getImgUrl());
        }
        if (Objects.isNull(poem.getTitle())){
            poem.setTitle(poemOld.getTitle());
        }
        return poemRepository.save(poem);
    }

    @Override
    public List<Poem> findAllPoem() {
        return poemRepository.findAll();
    }

    @Override
    public Poem findPoemById(String id) {
        return poemRepository.findById(id).orElse(null);
    }
}
